package com.yunkeji.admin.controller.common;

import com.yunkeji.common.utils.redis.CacheUtils;
import com.yunkeji.dao.domain.SysIpDeviceBanned;
import com.yunkeji.dao.mapper.sys.SysIpDeviceBannedMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 定时任务类
 *
 * @Author:雷擎宇
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SchedulingController{

    private final SysIpDeviceBannedMapper mapper;

    /**
     * 定时同步redis的IP和设备封禁记录（1000 * 60 * 30：半小时执行一次）
     */
    @Scheduled(fixedDelay = 1000 * 60 * 30)
    private void syncBannedRedis(){
        List<SysIpDeviceBanned> list = mapper.selectList();
        Set<Object> keys = CacheUtils.keys("banned");
        if(null == keys){
            keys = new HashSet<>();
        }
        if(list.size() != keys.size()){
            log.info("正在同步redis的IP和设备封禁记录....");
            for (SysIpDeviceBanned item : list) {
                String target = item.getTarget();
                if(!keys.contains(target)){
                    CacheUtils.put("banned", target, target);
                }
            }
        }
    }
}
